package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
             /*
            用户添加菜品/套餐后，点击加入购物车 页面发送add请求
            1.在线程上获取唯一的用户id 设置给购物车 才知道当前数据是谁的购物车数据
            2.获取传过来的购物车对象的 dishId
            3.对dishId进行判断,如果为空 说明添加的套餐，如果不为空说明添加的是菜品
            4.根据对应条件查询到当前的菜品/套餐对象
            4.如果再次添加 则需要判断当前添加的对象是否存在 不存在就直接添加 存在就+1
         */
        //1.设置用户id
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //2.获取id
        Long dishId = shoppingCart.getDishId();
        //4.设置条件
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        //3.判断添加的是菜品还是套餐
        if (dishId != null) {
            //5.1添加的是菜品
            lqw.eq(ShoppingCart::getDishId, dishId); //设置条件 菜品id
        } else {
            //5.2添加的是套餐    设置条件 套餐id
            lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        //6.下面就要开始查询添加的对象
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart one = this.getOne(lqw); //此时是在数据库查询购物车对象
        //7.判断
        if (one != null) {
            Integer number = one.getNumber();
            one.setNumber(number + 1);
            this.updateById(one);
        } else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            one = shoppingCart;
        }
        return one;
    }

    @Override
    public void clean() {
        //用户id
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        //清空
        this.remove(lqw);
    }
}
